/**
 * Created by WUJO2 on 7/15/2016.
 */

var startServer;

$(document).ready(function () {
    checkIfTCPServerRunning();
    renderTriggerButton();
    setInterval(getTCPStatus, 2500);
});

$("#tcpServerTrigger").click(function () {
    if (startServer == null) {
        startServer = true;
    }
    if (startServer) {
        $.get("/httpServer/startCRMServer");
        startServer = false;
    } else {
        $.get("/httpServer/stopCRMServer");
        startServer = true;
    }
    renderTriggerButton();
});

function checkIfTCPServerRunning() {
    $.ajax({
        url: "/httpServer/isTCPServerRunning",
        async: false,
        success: function (data) {
            startServer = !data["boolean"];
        }
    });
}

function renderTriggerButton() {
    var trigger = $("#tcpServerTrigger");
    if (startServer) {
        trigger.attr("class", "btn btn-lg btn-success");
        trigger.html("Start TCP server");
    } else {
        trigger.attr("class", "btn btn-lg btn-danger");
        trigger.html("Stop TCP server");
    }
}

function getTCPStatus() {
    var statusBarBody = $("#statusBarBody");
    $.get("/httpServer/serverStatus", function (statusList) {
        if (statusList == null) {
            statusBarBody.empty();
        } else {
            var htmlContent = [];
            for (var i = 0; i < statusList.length; i++) {
                htmlContent.push('<tr">');
                htmlContent.push('<td>' + (i + 1) + '</td>');
                htmlContent.push('<td>' + statusList[i]["ipAddress"] + '</td>');
                htmlContent.push('<td>' + statusList[i]["dateOfConnection"] + '</td>');
                htmlContent.push('</tr>');
            }
            statusBarBody.html(htmlContent.join(''));
        }
    });
}